package com.ztom.top100;

/**
 * 环形链表
 * <p>
 * https://leetcode-cn.com/problems/linked-list-cycle/
 *
 * @author ZhangTao
 */
public class Code50HasCycle {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        // 快慢指针: 相遇即有环
        ListNode fast = head;
        ListNode slow = head;

        // fast 连走两步, 每步都要判空
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }
}
